<script setup lang="tsx">
import { ref, computed, onMounted } from 'vue';
import { $t } from '@/locales';
import { NLayout, NLayoutHeader, NLayoutContent, NButton, NCard, NInputNumber } from 'naive-ui';
import { fetchCategoryItems, commitAreaScore, commitCategoryScore, fetchCategoryCompletedAreas } from '@/service/api';
import { useRoute } from 'vue-router';
import { useRouterPush } from '@/hooks/common/router';

// 路由
const { routerPushByKey } = useRouterPush();

// 获取到进入页面的ID
const route = useRoute();

// 区域数据
const areas = ref<Api.SystemManage.PutAreaScoreVo[] | undefined>([]);
// 选中区域的下标
const selectedAreaIndex = ref<number | null>(null);
// 已完成区域的下标
const completedAreas = ref<string[]>([]);
// name of hosp
const hospName = ref<string | null>(null);

// 加载数据
onMounted(async () => {
  const hospCheckCategoryId = route.params.id as string;
  const response = await fetchCategoryItems(hospCheckCategoryId);

  console.log(response.data?.data)
  areas.value = response.data?.data.areas;
  hospName.value = response.data?.data.hospName;
  try {
    // 获取已完成的区域数据
    const checkRes = await fetchCategoryCompletedAreas(hospCheckCategoryId);
    
    // 假设 checkRes 返回的是一个字符串数组，直接将所有 areaId 添加到 completedAreas 中
    // console.log(checkRes && Array.isArray(checkRes));
    // console.log(Array.isArray(checkRes.data));
    // console.log(Array.isArray(checkRes.data.data));
    // console.log(checkRes)
    // console.log(checkRes.data)
    if (checkRes.data && Array.isArray(checkRes.data.data)) {
      // 将所有的 areaId 添加到 completedAreas 中
      completedAreas.value.push(...checkRes.data.data); // 使用扩展运算符将数组元素逐个添加
    }
  } catch (error) {
    console.error('获取已完成区域失败:', error);
  }
  return response;
});

// 当前选中的区域
const selectedArea = computed<Api.SystemManage.PutAreaScoreVo | null>(() => {
  if(areas.value && selectedAreaIndex.value !== null){
    console.log("selected area: " + areas.value[selectedAreaIndex.value]);
    return areas.value[selectedAreaIndex.value];
  }
  return null;
})

// 判断是否所有区域已完成
const allAreasCompleted = computed(() => {
  return completedAreas.value?.length === (areas.value??[]).length;
});

// 选择区域
const selectArea = (index: number) => {
  
  // 检查当前选中的区域是否已经完成
  if (completedAreas.value.includes(areas.value[index].areaScore.areaId)) {
    return;
  }

  selectedAreaIndex.value = index;
};

// 更新得分
const updateScore = (item: Api.SystemManage.PutItemScoreVo) => {
  var computeScore = item.score - item.itemScore.deficiencyScore * item.itemScore.deficiencyNumber;
  item.itemScore.score = computeScore >= 0 ? computeScore : 0;
};

// 计算区域的总分数
const areaTotalScore = computed(()=>{
  if(!selectedArea.value){
    return 0;
  }
  selectedArea.value.areaScore.score = selectedArea.value.items.reduce((sum, item) => sum + (item.itemScore.score || 0), 0)
  selectedArea.value.areaScore.deficiencyNumber = selectedArea.value.items.reduce((sum, item) => sum + (item.itemScore.deficiencyNumber || 0), 0)
  return selectedArea.value.areaScore.score;
});

// 提交区域得分
const submitAreaScore = async () =>{
  
  if(!areas.value || selectedAreaIndex.value === null){
    return;
  }
  try{
    
    console.log(areas.value[selectedAreaIndex.value]);
    const response = await commitAreaScore(areas.value[selectedAreaIndex.value]);
    if (response.error) {
      return;
    } 
     // 更新按钮类型为 success
    if (completedAreas.value && !completedAreas.value.includes(selectedArea.value.areaScore.areaId)) {
      completedAreas.value.push(selectedArea.value.areaScore.areaId);
    }
    console.log("completedAreas : " + completedAreas.value);

    window.$message?.success(`${selectedArea.value.areaName} 区域得分提交成功`);
    // 清空选中区域
    selectedAreaIndex.value = null;
  }catch(error){
    // 异常处理
    console.error(error);
    window.$message?.error('网络错误，请稍后重试');
  }
}

const submitHospCategoryScore = async () => {
  if(completedAreas.value?.length !== (areas.value??[]).length){
    window.$message?.error('未完成打分任务');
  }
  try{
      console.log(route.params.id as string)
      const response = await commitCategoryScore(route.params.id as string); 
      if (response.error) {
        return;
      }
      // 进入批次考核界面
      routerPushByKey('checkbatch')
        .then(() => {
          console.log('成功跳转到打分界面');
      })
        .catch(error => {
          console.error('跳转失败:', error);
      });
  }catch(error){
    // 异常处理
    console.error(error);
    window.$message?.error('网络错误，请稍后重试');
  }
}

</script>

<template>
  <NLayout class="layout">
      <NLayoutHeader class="layout-header">
        <NCard>
          <div class="button-container">
            <!-- 左侧动态生成的按钮 -->
            <div class="left-buttons">
              <NButton
                v-for="(area, index) in areas"
                :key="area.areaScore.areaId"
                :type="completedAreas?.includes(area.areaScore.areaId) ? 'success' : 'default'"
                :disabled="area.areaScore.deleteFlag === 0 ? true : false"
                @click="selectArea(index)">
                {{ area.areaName }}
              </NButton>
            </div>
          
            <!-- 右侧的提交按钮 -->
            <div class="right-button">
              <NButton
                type="primary"
                :disabled="!allAreasCompleted"
                @click="submitHospCategoryScore">
                提交
              </NButton>
            </div>
          </div>
        </NCard>
      </NLayoutHeader>


      <NLayoutContent>
        <div class="card-container">
          <div class="card-wrapper" v-for="(item, index) in selectedArea?.items" :key="item.itemScore.id">
            <NCard :title="item.itemName" class="custom-card">
              <NText class="standard-text">
                评分标准为 : {{ item.itemStandard }}
              </NText>
              <div class="card-content">
                <div class="issue-count">
                  <span>问题计数 :</span>
                  <NInputNumber
                    v-model:value="item.itemScore.deficiencyNumber"
                    :min="0"
                    :step="1"
                    @update:value="updateScore(item)"/>
                </div>
              </div>
              <div style="margin-top: 10px;" v-show="item.itemScore.deficiencyNumber > 0">
                <NText>事件发生点:{{hospName}} </NText>
                <NInput 
                  type="text" 
                  placeholder="问题留痕描述(选填)"  
                  v-model:value="item.remark" 
                  maxlength="30" 
                  show-count 
                  clearable />
              </div>
              <div class="final-score">
                  得分: <span class="score-value">{{ item.itemScore.score }}</span>           
              </div>
            </NCard>
          </div>
        </div>
      </NLayoutContent>

      <NLayoutFooter v-show="selectedAreaIndex !== null" class="layout-footer">
        <NCard class="footer-card">
          <div class="footer-content">
            <NText>
              该区域的总分为 : <span class="total-score">{{ areaTotalScore }}</span>
            </NText>           
            <NButton type="primary" @click="submitAreaScore" class="submit-button">
              提交{{selectedArea?.areaName}}区域分数 
            </NButton>        
          </div>
        </NCard>
      </NLayoutFooter>

  </NLayout>
</template>

<style scoped>

.button-container {
  display: flex;
  justify-content: space-between; /* 左右两部分分开 */
  align-items: center; /* 垂直居中 */
}

/* 左侧按钮组样式 */
.left-buttons {
  display: flex;
  flex-wrap: wrap; /* 如果按钮多行显示 */
  gap: 16px; /* 按钮之间的间距 */
}

/* 右侧提交按钮样式 */
.right-button {
  margin-left: auto; /* 自动占位将按钮推到右边 */
}

/* 容器样式 */
.card-container {
  display: flex;
  flex-wrap: wrap; 
  gap: 16px;
}

/* 卡片包装器样式 */
.card-wrapper {
  flex: 0 0 500px; /* 固定卡片宽度 */
  box-sizing: border-box; /* 包括边框和内边距 */
}

/* 自定义卡片样式 */
.custom-card {
  border: 1px solid #e0e0e0;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 16px;
  background-color: #fff;
}

.standard-text{
  height: 80px; /* 固定高度 */
  line-height: 1.5; /* 行高，控制文字间距 */
  overflow: hidden; /* 超出内容隐藏 */
  text-overflow: ellipsis; /* 超出内容显示省略号 */
}

/* 卡片内容样式 */
.card-content {
  margin-top: 16px;
}

/* 问题计数器样式 */
.issue-count {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
  font-size: 16px;
  font-weight: bold; /* 加粗 */
  color: #444; /* 深色强调 */
}

/* 最终得分样式 */
.final-score {
  margin-top: 24px;
  text-align: right; /* 靠右对齐 */
  font-size: 16px;
  font-weight: bold; /* 加粗 */
  color: #222; /* 深色强调 */
}

/* 最终得分数值样式 */
.score-value {
  font-size: 20px;
  font-weight: bold; /* 放大加粗 */
  color: #d9534f; /* 使用红色或强调颜色 */
}

.layout-header {
  margin-bottom: 20px;
  display: flex;
}

.layout-content {
  flex: 1; 
  overflow: auto; 
}

.layout-footer{
  justify-content: end;
  margin-top: 20px;
}

.card-content {
  display: flex;
  justify-content: space-between; /* 左右两边 */
  align-items: center; /* 垂直居中对齐 */
}

/* 内容行样式 */
.footer-content {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between; /* 左右对齐 */
  font-size: 18px; /* 字体放大 */
}

/* 总分部分样式 */
.area-total {
  display: flex;
  align-items: center;
  gap: 8px; /* 文本与分数之间的间距 */
  font-weight: bold; /* 加粗总分部分 */
  color: #333; /* 深色强调 */
}

.total-score {
  font-size: 20px; /* 放大分数字体 */
  color: #d9534f; /* 红色强调分数 */
}

/* 提交按钮样式 */
.submit-button {
  font-size: 16px; 
  padding: 8px 16px; 
}
</style>
